package cn.edu.zjicm.wordsnet_d.activity;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.RelationShip;
import cn.edu.zjicm.wordsnet_d.data.test.ConsolidateManager;
import cn.edu.zjicm.wordsnet_d.data.test.Question;
import cn.edu.zjicm.wordsnet_d.data.test.TestActivityInterface;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode2ForConsolidateFragment;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode34ForConsolidateFragment;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;
import cn.edu.zjicm.wordsnet_d.view.WriteView;

public class ExamConsolidateActivity extends WordBaseActivity implements TestActivityInterface {
	public static void startActivity(Context context) {
		Intent i = new Intent(context, ExamConsolidateActivity.class);
		context.startActivity(i);
	}

	// private LinearLayout examConsolidateFragmentContainer;
	private ProgressBar consolidateProgressBar1;
	private ProgressBar consolidateProgressBar2;
	private ProgressBar consolidateProgressBar3;
	private ProgressBar consolidateProgressBar4;
	private TextView consolidateProgressBarText1;
	private TextView consolidateProgressBarText2;
	private TextView consolidateProgressBarText3;
	private TextView consolidateProgressBarText4;

	private ConsolidateManager manager;
	private Context context;
	private Question rQuestion; // 当前测试题
	public ConsolidateManager.QUESTION_URGENCY currentQuestionUrgency;

	private ExamRunMode34ForConsolidateFragment fragmentChoiceMode;
	private ExamRunMode2ForConsolidateFragment fragmentWithoutRelationshipMode;
	private ViewFlipper mConsolidateModeFlipper, mMainFlipper;

	private TextView mRestViewTextView, mRestViewTextView2;
	private ImageView mRestViewImage;

	private PopupWindow mWriteWindow;

	private enum testMode {
		multipleChooseMode, classicalMode
	}

	private testMode mode;

	private Button mRestViewContinueBtn;
	public CURRENT_WORD_FM_DEGREE_STATE currentWordFMDegreeState = CURRENT_WORD_FM_DEGREE_STATE.FAMILIAR;

	public static enum CURRENT_WORD_FM_DEGREE_STATE {
		UN_FAMILIAR, FAMILIAR, TOO_EASY
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设定调整音量为媒体音量
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("巩固熟词");
		setContentView(R.layout.activity_exam_consolidate);
		findViews();

		initData();
	}

	private void findViews() {
		consolidateProgressBar1 = (ProgressBar) findViewById(R.id.progressbar_consolidate1);
		consolidateProgressBar2 = (ProgressBar) findViewById(R.id.progressbar_consolidate2);
		consolidateProgressBar3 = (ProgressBar) findViewById(R.id.progressbar_consolidate3);
		consolidateProgressBar4 = (ProgressBar) findViewById(R.id.progressbar_consolidate4);
		consolidateProgressBarText1 = (TextView) findViewById(R.id.progressbar_consolidate_text1);
		consolidateProgressBarText2 = (TextView) findViewById(R.id.progressbar_consolidate_text2);
		consolidateProgressBarText3 = (TextView) findViewById(R.id.progressbar_consolidate_text3);
		consolidateProgressBarText4 = (TextView) findViewById(R.id.progressbar_consolidate_text4);

		mConsolidateModeFlipper = (ViewFlipper) findViewById(R.id.exam_consolidate_fragment_viewflipper);
		mMainFlipper = (ViewFlipper) findViewById(R.id.exam_consolidate_main_flipper);

		mRestViewTextView = (TextView) findViewById(R.id.exam_consolidate_rest_time);
		mRestViewTextView2 = (TextView) findViewById(R.id.exam_consolidate_rest_time2);
		mRestViewContinueBtn = (Button) findViewById(R.id.exam_consolidate_click_to_continue);
		mRestViewImage = (ImageView) findViewById(R.id.exam_consolidate_rest_image);

		setRightButton1("", R.drawable.calendar_info_selector, new OnClickListener() {
			@Override
			public void onClick(View v) {
				showInfoDialog();
			}
		});
	}

	private void initData() {
		this.context = ExamConsolidateActivity.this;
		initTestMode(AppPreference.getConsolidateMode(context));
		mMainFlipper.setDisplayedChild(0);
		manager = new ConsolidateManager(context);
		showChooseModeDialog();
		if (manager.hasWordsToConsolidate) {
			currentQuestionUrgency = manager.getCurrentQuestionUrgency(manager.getCurrentIndex());
			nextQuestion();
		} else {
			noWordsToConsolidate();
		}
	}

	private testMode initTestMode(int index) {
		switch (index) {
		case 0:
			mode = testMode.multipleChooseMode;
			break;
		case 1:
			mode = testMode.classicalMode;
			break;
		default:
			mode = testMode.multipleChooseMode;
			break;
		}
		return mode;
	}

	private void nextQuestion() {
		rQuestion = manager.nextQuestion();
		startQuestion(rQuestion);
		// if (rQuestion != null) {
		// ConsolidateManager.QUESTION_URGENCY qu =
		// manager.getCurrentQuestionUrgency(manager.getCurrentIndex());
		// if (qu != currentQuestionUrgency)
		// showRestView(qu);
		// startQuestion(mode, rQuestion);
		// } else {
		// stopTest();
		// }
	}

	private void startQuestion(Question rQuestion) {
		if (rQuestion != null) {
			ConsolidateManager.QUESTION_URGENCY qu = manager.getCurrentQuestionUrgency(manager.getCurrentIndex());
			if (qu != currentQuestionUrgency)
				showRestView(qu);
			RelationShip r = rQuestion.getRelationShip();
			if (null == r || mode == testMode.classicalMode) {
				modeWithoutRelationship();
			} else {
				modeChoice(r);
			}
		} else {
			stopTest();
		}
	}

	private void modeChoice(RelationShip r) {
		if (null == fragmentChoiceMode) {
			fragmentChoiceMode = new ExamRunMode34ForConsolidateFragment(r, ExamConsolidateActivity.this);
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ft.add(R.id.exam_consolidate_fragment_container, fragmentChoiceMode);
			ft.commit();
		} else {
			Log.i("word", r.getWord_str());
			fragmentChoiceMode.initViewForNewRelationShip(r);
		}
		mConsolidateModeFlipper.setDisplayedChild(0);
	}

	private void modeWithoutRelationship() {
		if (null == fragmentWithoutRelationshipMode) {
			fragmentWithoutRelationshipMode = new ExamRunMode2ForConsolidateFragment(rQuestion.getWord(), ExamConsolidateActivity.this);
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ft.add(R.id.exam_consolidate_fragment_container2, fragmentWithoutRelationshipMode);
			ft.commit();
		} else
			fragmentWithoutRelationshipMode.initViewForNewWord(rQuestion.getWord());
		mConsolidateModeFlipper.setDisplayedChild(1);
	}

	private void showRestView(ConsolidateManager.QUESTION_URGENCY qu) {
		switch (currentQuestionUrgency) {
		case TODAY:
			mRestViewTextView.setText("恭喜你，完成了第一阶段的巩固任务");
			showRestViewInit(qu);
			break;
		case IN_3_DAYS:
			mRestViewTextView.setText("恭喜你，完成了第二阶段的巩固任务");
			showRestViewInit(qu);
			break;
		case IN_7_DAYS:
			mRestViewTextView.setText("恭喜你，完成了第三阶段的巩固任务");
			showRestViewInit(qu);
			break;
		// case AFTER_7_DAYS:
		// mRestViewTextView.setText("恭喜你，完成了第三阶段的巩固任务");
		// showRestViewInit(qu);
		// break;
		}
	}

	private void showRestViewInit(ConsolidateManager.QUESTION_URGENCY qu) {
		currentQuestionUrgency = qu;
		mMainFlipper.setDisplayedChild(1);
		mRestViewTextView2.setVisibility(View.INVISIBLE);
		mRestViewImage.setImageResource(R.drawable.cosolidate_complete);
		mRestViewContinueBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mMainFlipper.setDisplayedChild(0);
			}
		});
	}

	private void setProgressBarData(int sum1, int sum2, int sum3, int sum4, int indexNum) {
		if (indexNum < sum1 && sum1 != 0) {
			consolidateProgressBar1.setProgress((int) (indexNum * 1.0 / sum1 * 100));
			consolidateProgressBar2.setProgress(0);
			consolidateProgressBar3.setProgress(0);
			consolidateProgressBar4.setProgress(0);

			consolidateProgressBarText1.setText(indexNum + "/" + sum1);
			consolidateProgressBarText2.setText(0 + "/" + sum2);
			consolidateProgressBarText3.setText(0 + "/" + sum3);
			consolidateProgressBarText4.setText(0 + "/" + sum4);
		} else if (indexNum < (sum1 + sum2) && sum2 != 0) {
			consolidateProgressBar1.setProgress(100);
			consolidateProgressBar2.setProgress((int) ((indexNum - sum1) * 1.0 / sum2 * 100));
			consolidateProgressBar3.setProgress(0);
			consolidateProgressBar4.setProgress(0);

			consolidateProgressBarText1.setText(sum1 + "/" + sum1);
			consolidateProgressBarText2.setText((indexNum - sum1) + "/" + sum2);
			consolidateProgressBarText3.setText(0 + "/" + sum3);
			consolidateProgressBarText4.setText(0 + "/" + sum4);
		} else if (indexNum < (sum1 + sum2 + sum3) && sum3 != 0) {
			consolidateProgressBar1.setProgress(100);
			consolidateProgressBar2.setProgress(100);
			consolidateProgressBar3.setProgress((int) ((indexNum - sum1 - sum2) * 1.0 / sum3 * 100));
			consolidateProgressBar4.setProgress(0);

			consolidateProgressBarText1.setText(sum1 + "/" + sum1);
			consolidateProgressBarText2.setText(sum2 + "/" + sum2);
			consolidateProgressBarText3.setText((indexNum - sum1 - sum2) + "/" + sum3);
			consolidateProgressBarText4.setText(0 + "/" + sum4);
		} else if (sum4 != 0) {
			consolidateProgressBar1.setProgress(100);
			consolidateProgressBar2.setProgress(100);
			consolidateProgressBar3.setProgress(100);
			consolidateProgressBar4.setProgress((int) ((indexNum - sum1 - sum2 - sum3) * 1.0 / sum4 * 100));

			consolidateProgressBarText1.setText(sum1 + "/" + sum1);
			consolidateProgressBarText2.setText(sum2 + "/" + sum2);
			consolidateProgressBarText3.setText(sum3 + "/" + sum3);
			consolidateProgressBarText4.setText((indexNum - sum1 - sum2 - sum3) + "/" + sum4);
		} else {
			consolidateProgressBar1.setProgress(0);
			consolidateProgressBar2.setProgress(0);
			consolidateProgressBar3.setProgress(0);
			consolidateProgressBar4.setProgress(0);

			consolidateProgressBarText1.setText(0 + "");
			consolidateProgressBarText2.setText(0 + "");
			consolidateProgressBarText3.setText(0 + "");
			consolidateProgressBarText4.setText(0 + "");
		}
	}

	public void updateResult() {
		if (null != manager)
			setProgressBarData(manager.getCosolidateNumsLatestToday(), manager.getCosolidateNumsLatestIn3Days(), manager.getCosolidateNumsLatestIn7Days(), manager.getCosolidateNumsLatestAfter7Days(),
					manager.getCurrentIndex());
	}

	private void showInfoDialog() {
		View view = LayoutInflater.from(this).inflate(R.layout.view_dialog_normal, null);
		TextView content = (TextView) view.findViewById(R.id.dialog_content);
		LinearLayout ll = (LinearLayout) view.findViewById(R.id.two_btn_layout);
		ll.setVisibility(View.GONE);
		String contentText = "页面底部的进度条表示了熟词复习的紧迫程度：\n  第一段：今天必须要巩固的熟词；\n  第二段：3天内须要巩固的熟词；\n  第三段：7天内须要巩固的熟词；\n  第四段：其余可巩固的熟词。\n\n您可以根据自己的需要来确定每天巩固的熟词量。“熟词”经过一定天数和次数的巩固后会自动转化为“太简单”。";
		content.setText(contentText);
		Button getIt = (Button) view.findViewById(R.id.got_it);
		getIt.setVisibility(View.VISIBLE);
		final MyDialog infoDialog = new MyDialog(this, view, R.style.mydialog, false);
		infoDialog.setCanceledOnTouchOutside(true);
		infoDialog.show();
		getIt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				infoDialog.dismiss();
			}
		});
	}

	@Override
	public void displayWriteView() {
		TypedValue typedValue = new TypedValue();
		getTheme().resolveAttribute(R.attr.spell_dialog_bg_blur, typedValue, true);
		mMainFlipper.setDisplayedChild(2);
		hideTitle();
	}

	ImageView playVoice = null;
	WriteView mWriteView = null;

	@Override
	public void showWriteWindow() {
		if (mWriteWindow == null) {
			View view = View.inflate(this, R.layout.window_write, null);
			ImageView writeAgainButton = (ImageView) view.findViewById(R.id.write_again_button);
			ImageView hintButton = (ImageView) view.findViewById(R.id.hint);
			ImageView closeButton = (ImageView) view.findViewById(R.id.write_close_button);
			playVoice = (ImageView) view.findViewById(R.id.play_voice_writeview);
			mWriteView = (WriteView) view.findViewById(R.id.write_view);

			writeAgainButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteView.reWrite();
				}
			});
			closeButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteWindow.dismiss();
				}
			});
			hintButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Toast.makeText(ExamConsolidateActivity.this, mWriteView.hint(), Toast.LENGTH_SHORT).show();
				}
			});
			playVoice.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteView.playOneWordVoice();
				}
			});
			mWriteWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			mWriteWindow.setFocusable(true);
			mWriteWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.transparent_bg_drawable));
			mWriteWindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					mMainFlipper.setDisplayedChild(0);
					showTitle();
				}
			});
		}

		if (playVoice != null) {
			if (NightModeUtil.isNightModeNow()) {
				if (FileManager.isVoiceFileExist(context, rQuestion.getWord())) {
					playVoice.setImageResource(R.drawable.write_view_play_voice_ico_night_selector);
				} else {
					playVoice.setImageResource(R.drawable.write_view_play_ico_unclickable_night);
				}
			} else {
				if (FileManager.isVoiceFileExist(context, rQuestion.getWord())) {
					playVoice.setImageResource(R.drawable.write_view_play_voice_ico_selector);
				} else {
					playVoice.setImageResource(R.drawable.write_view_play_ico_unclickable);
				}
			}
		}
		mWriteView.init(rQuestion.getWord());
		mWriteView.reWrite();
		if (mWriteView.isToShowKeyBoard()) {
			mWriteWindow.showAtLocation(mMainFlipper, Gravity.TOP, 0, 0);
		} else
			mWriteWindow.showAtLocation(mMainFlipper, Gravity.CENTER, 0, 0);

	}

	@Override
	public void next(ANSWER_RESULT result) {
		if (rQuestion == null)
			return;
		switch (result) {
		case RIGHT:
			manager.rightAnswerBtn(rQuestion);
			break;
		case WRONG:
			manager.wrongAnswerBtn(rQuestion);
			break;
		case AGAIN:
			manager.wrongAnswerAndTestAgainBtn(rQuestion);
			break;
		}

		if (currentWordFMDegreeState != CURRENT_WORD_FM_DEGREE_STATE.FAMILIAR) {
			switch (currentWordFMDegreeState) {
			case TOO_EASY:
				manager.setWordToTooEasyNormal(rQuestion);
				break;
			case UN_FAMILIAR:
				manager.setWordToUnFamiliar(rQuestion);
				break;
			}
		}
		currentWordFMDegreeState = CURRENT_WORD_FM_DEGREE_STATE.FAMILIAR;
		rQuestion = null;
		nextQuestion();
	}

	@Override
	public void removeCurWord() {

	}

	@Override
	public void showDownloadVoiceWindow(Handler handler) {

	}

	private void stopTest() {
		mRestViewTextView.setText("恭喜你，完成了所有的熟词任务，\n明日再战吧！");
		mRestViewImage.setImageResource(R.drawable.cosolidate_complete);
		mRestViewTextView2.setVisibility(View.INVISIBLE);
		mMainFlipper.setDisplayedChild(1);
		mRestViewContinueBtn.setText("完成");
		mRestViewContinueBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	public void setCurrentWordStates(CURRENT_WORD_FM_DEGREE_STATE states) {
		this.currentWordFMDegreeState = states;
	}

	public void noWordsToConsolidate() {
		mRestViewTextView.setText("您好，您现在没有熟词需要复习哦~ ");
		mRestViewTextView2.setVisibility(View.VISIBLE);
		String showContent = "     我们会根据您的学习进度智能安排需要复习的熟词。\n\n     有需要复习的熟词时，按钮的字体会变成黑色。 ";
		mRestViewTextView2.setText(showContent);
		mRestViewImage.setImageResource(R.drawable.cosolidate_none);
		mMainFlipper.setDisplayedChild(1);
		mRestViewContinueBtn.setText("好的，我知道了");
		mRestViewContinueBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	public void showChooseModeDialog() {
		if (-1 != AppPreference.getConsolidateMode(context))
			return;
		View view = LayoutInflater.from(this).inflate(R.layout.view_choose_consolidate_mode, null);
		final RadioButton radioButton1 = (RadioButton) view.findViewById(R.id.consolidate_mode_radiobutton1);
		radioButton1.setChecked(true);
		final RadioButton radioButton2 = (RadioButton) view.findViewById(R.id.consolidate_mode_radiobutton2);
		final CheckBox rememberMe = (CheckBox) view.findViewById(R.id.remember_me);
		final Button buttonOK = (Button) view.findViewById(R.id.dialog_btn_ok);
		final MyDialog showConsolidateDialog = new MyDialog(this, view, R.style.mydialog, false);
		showConsolidateDialog.setCanceledOnTouchOutside(false);

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int checkedIndex = -1;
				if (radioButton1.isChecked()) {
					checkedIndex = 0;
				} else if (radioButton2.isChecked()) {
					checkedIndex = 1;
				}
				if (rememberMe.isChecked()) {
					AppPreference.setConsolidateMode(context, checkedIndex);
				}
				if (manager.hasWordsToConsolidate) {
					initTestMode(checkedIndex);
					startQuestion(rQuestion);
					showConsolidateDialog.dismiss();
				} else {
					showConsolidateDialog.dismiss();
					noWordsToConsolidate();
				}
				
			}
		});
		showConsolidateDialog.show();
	}

}
